# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(scatterplot3d)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

parent <- "./"
createWhenNoExist(parent)

sampleColDf <- read.csv(opt$sc, header = T,  stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))

pcDataFileName <- paste0(parent, "/PCA_Score.csv")
pc123 <- read_csv(pcDataFileName) %>%
    rename(SampleID = X1) %>%
    select(c("SampleID", "PC1", "PC2","PC3")) %>%
    left_join(sampleInfo, by = c("SampleID")) %>%
    left_join(sampleColDf, by = c("ClassNote"))

parameterFileName <- paste0(parent, "/PCA_R2.csv")
parameterData <- read.csv(parameterFileName, header = T, stringsAsFactors = F, comment.char = "")

impoPc1 <- parameterData[1, "PC1"]
impoPc1 <- round(impoPc1 * 100, 2)
impoPc2 <- parameterData[1, "PC2"]
impoPc2 <- round(impoPc2 * 100, 2)
impoPc3 <- parameterData[1, "PC3"]
impoPc3 <- round(impoPc3 * 100, 2)

fileName <- paste0(parent, "/PC123_Score_3D.pdf")

pdf(fileName, width = 8, height = 8)

opar <- par(no.readonly = TRUE)
par(family = "Times")

scatterplot3d(pc123$PC1, pc123$PC2, pc123$PC3, color = pc123$col, main = "", pch = 20, col.axis = "grey",
mar = c(5, 3, 1, 3) + 0.1, cex.symbols = 6, xlab = paste0("PC1(", impoPc1, "%)"), ylab = paste0("PC2(", impoPc2, "%)"),
zlab = paste0("PC3(", impoPc3, "%)"), angle = 60, cex.lab = 2, cex.axis = 1.5)

par(opar)

dev.off()
